const app = getApp();

Page({
  data: {
    loading: false,
    withdrawList: [], // 提现记录列表
    page: 1,
    pageSize: 20,
    hasMore: true
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '提现记录'
    });
    this.fetchWithdrawHistory();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.refreshData();
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      withdrawList: [],
      hasMore: true
    });
    this.fetchWithdrawHistory();
  },

  // 获取提现记录
  fetchWithdrawHistory() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    if (this.data.loading) return;

    this.setData({ loading: true });

    wx.request({
      url: `${ip}/api/riders/withdraw/history`,
      method: 'GET',
      data: {
        riderId: riderId,
        page: this.data.page,
        pageSize: this.data.pageSize
      },
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newList = (res.data.data || []).map(item => ({
            ...item,
            statusText: this.getStatusText(item.status),
            statusClass: this.getStatusClass(item.status),
            createTimeText: this.formatTime(item.createTime),
            completeTimeText: item.completeTime ? this.formatTime(item.completeTime) : ''
          }));
          const withdrawList = this.data.page === 1 ? newList : [...this.data.withdrawList, ...newList];

          this.setData({
            withdrawList: withdrawList,
            hasMore: newList.length === this.data.pageSize,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取记录失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: '处理中',
      1: '已到账',
      2: '已拒绝',
      3: '已取消'
    };
    return statusMap[status] || '未知状态';
  },

  // 获取状态样式类
  getStatusClass(status) {
    const classMap = {
      0: 'processing',
      1: 'success',
      2: 'failed',
      3: 'cancelled'
    };
    return classMap[status] || 'processing';
  },

  // 查看提现详情
  onWithdrawTap(e) {
    const withdraw = e.currentTarget.dataset.withdraw;
    const statusText = this.getStatusText(withdraw.status);
    const timeText = this.formatTime(withdraw.createTime);
    
    let content = `提现金额：¥${withdraw.amount}\n`;
    content += `申请时间：${timeText}\n`;
    content += `状态：${statusText}`;
    
    if (withdraw.remark) {
      content += `\n备注：${withdraw.remark}`;
    }

    wx.showModal({
      title: '提现详情',
      content: content,
      showCancel: false,
      confirmText: '确定'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      });
      this.fetchWithdrawHistory();
    }
  },

  // 跳转到提现页面
  goToWithdraw() {
    wx.navigateTo({
      url: '/pages/withdraw/index'
    });
  }
});
